package main

import (
	"fmt"
	"github.com/panjf2000/gnet/v2"
	log "github.com/sirupsen/logrus"
)

type Server1 struct {
	gnet.BuiltinEventEngine
	eng       gnet.Engine
	addr      string
	multicore bool
}

func (server *Server1) OnBoot(eng gnet.Engine) gnet.Action {
	server.eng = eng
	log.Printf("echo server with multi-core=%t is listening on %s\n", server.multicore, server.addr)
	return gnet.None
}

func (server *Server1) OnTraffic(c gnet.Conn) (action gnet.Action) {
	data, err := c.Next(-1) // -1表示读取conn中的所有数据
	if err != nil {
		log.Warnln("[OnTraffic]-读数据异常：" + err.Error())
	}
	log.Infof("[OnTraffic]-读取到%d个数据，内容为%s", len(data), string(data))
	_, _ = c.Write(data)
	return gnet.None
}

func main() {
	handler := &Server1{
		addr:      fmt.Sprintf("localhost:%d", 7878),
		multicore: true,
	}
	err := gnet.Run(handler, handler.addr, gnet.WithMulticore(handler.multicore))
	if err != nil {
		log.Errorln("server启动异常:" + err.Error())
	}
}
